package org.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.cache.RedisCache;
import org.example.dao.UserDao;
import org.example.entity.User;
import org.example.entity.vo.LoginUser;
import org.example.entity.vo.LoginUserInfo;
import org.example.result.R;
import org.example.service.UserService;
import org.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户信息表(User)表服务实现类
 *
 * @author zxp
 * @since 2022-08-09 11:10:03
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    RedisCache redisCache;
    /**
     * @param user
     * @return
     */
    @Override
    public R login(LoginUserInfo user) {
        //        对用户进行认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
//        生成没通过给出的错误信息
        if(Objects.isNull(authenticate))
        {
            return R.error();
        }
//        通过给出jwt
        LoginUser principal =(LoginUser) authenticate.getPrincipal();
        String token = JwtUtils.generateToken(principal);
        Long userId = principal.getUser().getUserId();
//        同时存入redis
        String key = "login:"+userId;
        System.out.println(principal.getAuthorities());
        redisCache.setCacheObject(key,principal);
        return R.ok().data("token", token);
    }

    /**
     * @return
     */
    @Override
    public R logout() {
        //        去获取context中的用户信息 删除redis中的缓存
        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getUserId();
        String key = "login:"+userId;
        redisCache.deleteObject(key);
        return R.ok().data("msg","退出成功");
    }
}

